package com.lyf.juc.practice.tools;

import org.junit.Test;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author LYF
 * @date 2022/6/23
 */
public class ToolClassTests {
    /*
    工具类：


     */
    CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
    CountDownLatch countDownLatch = new CountDownLatch(6);
    Semaphore semaphore = new Semaphore(3);
    @Test
    public void test1(){
        for(int i=0;i<6;i++){
            final int  finalI = i;
            new Thread(()->{
//                try {
//                    TimeUnit.SECONDS.sleep(1);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                System.out.println("thread-"+finalI+" get ");
                countDownLatch.countDown();
            }).start();
        }

        try {
            countDownLatch.await();
            System.out.println("已获取三个同意，执行");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    @Test
    public void test2(){
        for(int i=1;i<6;i++){
            final  int finalI  = i;
            new Thread(()->{
                while(true){
                    try {
                        // 获取信号量
                        semaphore.acquire();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //
                    System.out.println("Thread-"+finalI+"抢到资源---");

                    try {
                        int random = new Random().nextInt(5);
                        TimeUnit.SECONDS.sleep(random);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    semaphore.release();
                    System.out.println("Thread-"+finalI+"释放资源");

                }

            }).start();
        }

//        try {
//            Thread.currentThread().wait();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        // 主线程--观察
        try {
            TimeUnit.SECONDS.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }



}
